package com.galaxy.service;

import com.galaxy.util.M;
import com.galaxy.util.RotateImageUtil;
import io.minio.BucketExistsArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.SetObjectTagsArgs;
import io.minio.errors.XmlParserException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

/**
 * @author anjie
 * @version 1.0
 * @date 2020/8/21 16:24
 * @email anjie@032t.com
 */
@Service
public class FileUpdateServiceImpl implements FileUpdateService {

    @Autowired
    MinioClient minioClient;

    //    @Value("${minio.bucketName}")
    private String bucketName;

    public M putFile(MultipartFile uploadFile, String bn, String path, String prefix) throws Exception {

        this.bucketName = bn;
        boolean b = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bn).build());
        if (!b) {
            return M.err();
        }

        InputStream inputStream = uploadFile.getInputStream();
        String originalFilename = uploadFile.getOriginalFilename();


        int i = originalFilename.lastIndexOf(".");
        String suffix;
        if (i != -1)
            suffix = originalFilename.substring(i);
        else
            suffix = "";

        // 如果是图片 处理一下图片避免ios设备的图片产生方向错误

        String[] strings = {".jpg",".jpeg"};


        for(String suff : strings){
            if(suff.equals(suffix)){
                InputStream pictureByInputStream = RotateImageUtil.getPictureByInputStream(inputStream,suffix);
                if(pictureByInputStream != null)
                    inputStream = pictureByInputStream;
                break;
            }
        }


        String uuid = UUID.randomUUID().toString();
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String format = sdf.format(d);
        String filepath;

        if (path != null && !path.equals("")) {
            filepath = path;
        } else {
            if (prefix != null)
                filepath = prefix;
            else
                filepath = format + "/" + uuid + suffix;
        }

        try {
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(filepath).stream(
                            inputStream, inputStream.available(), -1)
                            .build()
            );
        } catch (XmlParserException e) {
            M err = M.err();
            err.setMsg("请求路径错误! 应当是 xxx/.../xxx.x..");
            return err;
        }

        //设置对象附加属性
        HashMap<String, String> TAGS = new HashMap<>();
        String contentType = uploadFile.getContentType();
        if (contentType != null)
            TAGS.put("contentType", contentType);
        TAGS.put("name", originalFilename);
        TAGS.put("size", String.valueOf(uploadFile.getSize()));
        minioClient.setObjectTags(
                SetObjectTagsArgs
                        .builder()
                        .bucket(bucketName)
                        .object(filepath)
                        .tags(TAGS)
                        .build()
        );

        System.out.println("path:"+filepath);
        System.out.println("name:"+originalFilename);
        System.out.println("suffix:"+suffix);

        return M.ok()
                .add("path", filepath)
                .add("name", originalFilename)
                .add("suffix", suffix);
    }

}
